import asyncHandler from "express-async-handler";
import User from "../models/userModel.js";
import generateToken from "../utils/generateToken.js";

//用户注册
const registerUser = asyncHandler(async (req, res) => {
  //获取用户名、邮箱和密码
  const { name, email, password } = req.body;
  //根据邮箱查询用户是否存在
  const userExists = await User.findOne({ email });
  //用户是否注册
  if (userExists) {
    res.status(400);
    throw new Error("邮箱已注册");
  }
  //添加新用户
  const user = await User.create({ name, email, password });
  //创建成功返回新用户信息
  if (user) {
    res.status(201).json({
      _id: user._id,
      name: user.name,
      email: user.email,
      isAdmin: user.isAdmin,
      token: generateToken(user._id),
    });
  } else {
    res.status(400);
    throw new Error("无效的用户数据");
  }
});

//用户登录，获取token
const authUser = asyncHandler(async (req, res) => {
  //获取邮箱和密码
  const { email, password } = req.body;
  //根据邮箱查询数据
  const user = await User.findOne({ email });
  //判断用户是否存在且密码是否正确
  if (user && (await user.matchPassword(password))) {
    res.json({
      _id: user._id,
      name: user.name,
      email: user.email,
      isAdmin: user.isAdmin,
      token: generateToken(user._id),
    });
  } else {
    res.status(401);
    throw new Error("邮箱或者密码错误");
  }
});

//获取成功登录用户详情，私密路由需要token
const getUserProfile = asyncHandler(async (req, res) => {
  //根据id查找对应用户的信息
  const user = await User.findById(req.user._id);
  if (user) {
    res.json({
      _id: user._id,
      name: user.name,
      email: user.email,
      isAdmin: user.isAdmin,
    });
  } else {
    res.status(404);
    throw new Error("用户不存在");
  }
});

//更新用户资料，私密路由需要token
const updateUserProfile = asyncHandler(async (req, res) => {
  //根据id查找对应用户的信息
  const user = await User.findById(req.user._id);

  //获取更新后的资料
  if (user) {
    user.name = req.body.name || user.name;
    user.email = req.body.email || user.email;
    if (req.body.password) {
      user.password = req.body.password;
    }
    const updateUser = await user.save();
    //返回更新后的信息
    res.json({
      _id: updateUser._id,
      name: updateUser.name,
      email: updateUser.email,
      isAdmin: updateUser.isAdmin,
      token: generateToken(updateUser._id),
    });
  } else {
    res.status(404);
    throw new Error("用户不存在");
  }
});

//获取所有用户
const getUsers = asyncHandler(async (req, res) => {
  const users = await User.find({});
  res.json(users);
});

//删除用户
const deleteUser = asyncHandler(async (req, res) => {
  //根据id删除对应用户
  const user = await User.findById(req.params.id);
  if (user) {
    await user.remove();
    res.json({ message: "用户已删除" });
  } else {
    res.status(404);
    throw new Error("查找不到当前用户");
  }
});

//获取单个用户
const getUserById = asyncHandler(async (req, res) => {
  //根据id获取对应用户
  const user = await User.findById(req.params.id).select("-password");
  if (user) {
    res.json(user);
  } else {
    res.status(404);
    throw new Error("查找不到当前用户");
  }
});

//编辑用户
const updateUserById = asyncHandler(async (req, res) => {
  //根据id编辑对应用户
  const user = await User.findById(req.params.id);
  //获取更新后的资料
  if (user) {
    user.name = req.body.name || user.name;
    user.email = req.body.email || user.email;
    user.isAdmin = req.body.isAdmin;
    const updateUser = await user.save();
    //返回更新后的信息
    res.json({
      _id: updateUser._id,
      name: updateUser.name,
      email: updateUser.email,
      isAdmin: updateUser.isAdmin,
    });
  } else {
    res.status(404);
    throw new Error("用户不存在");
  }
});

export {
  registerUser,
  authUser,
  getUserProfile,
  updateUserProfile,
  getUsers,
  deleteUser,
  getUserById,
  updateUserById,
};
